<?php
/************************FoxPHP威客系统************************/
/*                                                            */
/*  FoxPHP.Com (C)2006-2016 FoxPHP Inc.                       */
/*  This is NOT a freeware, use is subject to license terms   */
/*  FoxPHP威客系统是商业软件,使用于商业用途请购买授权         */
/*  V3.0 2016.3                                               */
/*  foxphp@aliyun.com                                         */
/*  http://www.foxphp.com                                     */
/*                                                            */
/**************************************************************/


namespace Member\Model;
use Think\Model;
use \Org\Util\String;
    
class MemberModel extends Model {
	public function _initialize(){
	}
	//protected $insertFields = array('username','usertype','typename','password','powercode','usergroup','groupname','email','unionid','uniontime','regip','dateline','mobile');
	
	//protected $updateFields = array('avatar','SecurityForm');
	
	//字段过滤-----------------------------------------------------------------------------------------------
	//protected $insertFields = array('title','status','rules','icon','color','allowdomainname','allowlogin','allowskillnumber','allowsendsms','feetype','taskfee','SecurityForm');
	//protected $updateFields = array('usertype','typename','password','powercode','usergroup','groupname','email','unionid','uniontime','regip','dateline','mobile','birthday','about','gender','area','phone','qq','provid','cityid','distid','provname','cityname','distname','address','SecurityForm');
	
	
	//字段检查-----------------------------------------------------------------------------------------------
	protected $_validate = array(
		//array('bankcard','require','请输入名称！'),
	);
	
	//数据过滤-----------------------------------------------------------------------------------------------
	function FormatData($field='info'){
		
		//信息
		if($field=='info'){
			
			$data['catid']=intval($_POST['catid']);
			
			if(!empty($_POST['Year'])){
				$data['birthday']=strtotime(intval($_POST['Year']).'-'.intval($_POST['Month']).'-'.intval($_POST['Day']));
			}
			
			$data['shopname']=String::msubstr(I('post.shopname'),0,50,C('S_CHARSET'),false);
			$data['about']=String::msubstr(I('post.about'),0,200,C('S_CHARSET'),false);
			
			if(intval($_POST['gender'])==1){
				$data['gender']=1;
			}elseif(intval($_POST['gender'])==2){
				$data['gender']=2;
			}else{
				$data['gender']=0;
			}
			
			if(empty($data['shopname'])){
				$this->error='请输入店铺名称!';
				return false;
			}
		}
		
		if($field=='idsecurity'){
			//手机是否验证
			if(!M('MemberCertificate')->token(false)->where(" uid=$this->uid AND type=2 AND status=5 ")->count()){
				$this->error='请输入手机认证后操作!';
				return false;
			}
			$data['loginsecurity']=$_POST['loginsecurity']=='on' ? 1 : 2;
			$data['paysecurity']=$_POST['paysecurity']=='on'? 1 : 2;
		}
		
		if($field=='bankcard'){
			$data['bankcard']=I('post.bankcard');
			if(!IsNum($data['bankcard'])){
				$data['bankcard']=I('post.bankcard','','email');
				if(!preg_match('/([\w]+)(\@)([\w]+)(\.)([\w]+)/',$data['bankcard'])){
					$this->error='请输入正确的支付宝帐号!';
					return false;
				}
			}
		}
		
		if($field=='location'){
			$data['longitude']=floatval($_POST['longitude']);
			$data['latitude']=floatval($_POST['latitude']);
			
			if(!$data['longitude'] && !$data['latitude']){
				$this->error='对不起!获取不到位置!';
				return false;
			}
			
			
			$ip=new \Behavior\IpBehavior();
			
			$result=$ip->ChangePosition($data['latitude'].','.$data['longitude']);
			
			if(!empty($result->result->cityCode)){
				$citycode=intval($result->result->cityCode);
				
				$citynamearr=M('CategoryCity')->where("apiid=$citycode")->find();
				
				if(!empty($citynamearr['catid'])){
					$cityid=$data['cityid']=$citynamearr['catid'];
					$data['cityname']=$citynamearr['name'];
					
					$upid=$citynamearr['upid'];
					$provnamearr=M('CategoryCity')->where("catid=$upid")->find();
					if(!empty($provnamearr['catid'])){
						$data['provname']=$provnamearr['name'];
						$data['provid']=$provnamearr['catid'];
					}
					
					$distnamearr=M('CategoryCity')->where("upid=$cityid")->select();
					if(!empty($distnamearr)){
						foreach($distnamearr as $distarr){
							if($distarr['name']==$result->result->addressComponent->district){
								$data['distname']=$distarr['name'];
								$data['distid']=$distarr['catid'];
							}
						}
					}	
				}
				
			}
			
		}
		
		if($field=='shop'){
			$data['catid']=intval($_POST['catid']);
			$data['shopname']=String::msubstr(I('post.shopname'),0,50,C('S_CHARSET'),false);
			if(empty($data['shopname'])){
				$this->error='请输入店铺名称!';
				return false;
			}
			
			if(empty($data['catid'])){
				$this->error='请输入店铺分类!';
				return false;
			}
		}

		//联系方式
		if($field=='contact'){
			$data['mobile']=IsNum($_POST['mobile']) ? String::msubstr($_POST['mobile'],0,13,C('S_CHARSET'),false) : 0;
			$data['area']=IsNum($_POST['area']) ? String::msubstr($_POST['area'],0,8,C('S_CHARSET'),false) : 0;
			$data['phone']=IsNum($_POST['phone']) ? String::msubstr($_POST['phone'],0,12,C('S_CHARSET'),false) : 0;
			$data['qq']=IsNum($_POST['qq']) ? String::msubstr($_POST['qq'],0,20,C('S_CHARSET'),false) : 0;
			$data['address']=String::msubstr(I('post.address','','string'),0,200,C('S_CHARSET'),false);
			
			//所在地---------------------------------------------------------------------------------
			$provid=$data['provid']=intval($_POST['provid']);
			
			$cityid=$data['cityid']=intval($_POST['cityid']);
			
			$distid=$data['distid']=intval($_POST['distid']);
			
			if($provid && $cityid && $distid){
			
				$provnamearr=M('CategoryCity')->where("catid=$provid")->find();
				
				$citynamearr=M('CategoryCity')->where("catid=$cityid")->find();
				
				$distnamearr=M('CategoryCity')->where("catid=$distid")->find();
				
				$data['provname']=$provnamearr['name'];
				
				$data['cityname']=$citynamearr['name'];
				
				$data['distname']=$distnamearr['name'];
			}
		}

		//分类
		if($data['catid']){
			$catid=$data['catid'];
			$categoryarr=M('Category')->token(false)->where("catid=$catid")->find();
			if(!empty($categoryarr['name'])){
				$data['category_name_1']=$categoryarr['name'];
			}
			
			if($categoryarr['upid']){
				$catid=$categoryarr['upid'];
				$categoryarr=M('Category')->token(false)->where("catid=$catid")->find();
			}
			
			if($categoryarr['name']){
				$data['category_name_2']=$categoryarr['name'];
			}
			
			if($categoryarr['upid']){
				$catid=$categoryarr['upid'];
				$categoryarr=M('Category')->token(false)->where("catid=$catid")->find();
			}
			
			if($categoryarr['name']){
				$data['category_name_3']=$categoryarr['name'];
			}
		}
		
		$data['SecurityForm']=I('post.SecurityForm','','string');
		return $data;
	}
	

	//用户名查询 获取一维数据
	function UserNameGetMember($username=''){
		$username=String::msubstr($username,0,32,C('S_CHARSET'),false);
		$username=strip_tags($username);
		$username=trim(htmlspecialchars($username,ENT_QUOTES,C('S_CHARSET')));
		$result=$this->where(" username='%s' ",$username)->find();
		if(intval($result['uid'])>0){
			return $result;
		}else{
			$this->error='数据不存在或有误!';
			return false;
		}
	}
	
	//用户UID 查询
	function UidGetMember($uid=0){ 
		$result=$this->token(false)->where(" uid=%d ",$uid)->find();
		if(intval($result['uid'])>0){
			unset($result['password']);
			unset($result['powercode']);
			unset($result['cookiecode']);
			unset($result['unionid']);
			return $result;
		}else{
			$this->error='数据不存在或有误!';
			return false;
		}
	}
	
	//VIP过期
	function VIPExpired(){
		if($this->uid){
			$user=$this->UidGetMember($this->uid);
			if(!empty($user['vipendtime'])){
				$vipendtime=intval($user['vipendtime']);
				if(@time()>$vipendtime && $vipendtime>0){
					$this->token(false)->where(" uid=$this->uid ")->save(array('vipendtime'=>0,'usergroup'=>3));
				}
			}
		}
	}
	
	//获取用户登录 状态 AJAX
	function LoginStatus(){
		if($this->uid>0){
			$memberarray=$this->where(" uid=%d ",array($this->uid))->field('uid,username,money,moneyin,moneyout,dialogread,noticeread')->find();
			if($memberarray['uid']){
				$memberarray['money']=number_format($memberarray['money']/100,2,'.',',');
				$memberarray['moneyin']=number_format($memberarray['moneyin']/100,2,'.',',');
				$memberarray['moneyout']=number_format($memberarray['moneyout']/100,2,'.',',');
				return $memberarray;
			}
		}else{
			return array();
		}
	}
	
	//更新会员信息
	function UpdateMember($field='info'){
		$post=$this->FormatData($field);
		if(!$post){
			$this->error=$this->getError();
			return false;
		}
		if ($this->create($post)){
			if($this->where(" uid=$this->uid ")->save()){
				return true;
			}
			return $this->getError();
		}else{
			return $this->getError();
		}
	}
	
	function FilePath($dir,$filetype,$newnamearr=array()){
		
		$dir1 = gmdate('Ym');
		$dir2 = gmdate('j');

		$filedir=$dir.'/'.$dir1;

		if(!is_dir($filedir)) {
			@mkdir($filedir,0777);
			WriteFile($filedir.'/index.html','');
		}

		$filedir=$filedir.'/'.$dir2;

		if(!is_dir($filedir)){
			@mkdir($filedir,0777);
			WriteFile($filedir.'/index.html','');
		}

		$newfilename=RandomText(8,1);

		$newfilenamearr[]=$filedir.'/'.$newfilename.'.'.$filetype;

		//组合新文件名	
		if(!empty($newnamearr) && is_array($newnamearr)){
			foreach($newnamearr as $name){
				$newfilenamearr[]=$filedir.'/'.$newfilename.'_'.$name.'.'.$filetype;
			}
		}			 

		return $newfilenamearr;
	}
	
	function IsPhoto($im,$savepath){
		
		$Imagedata = @GetImageSize($im);

		switch ($Imagedata[2]){
			case 1:
			$im = @imagecreatefromgif($im);
			break;
			case 2:
			$im = @imagecreatefromjpeg($im);
			break;
			case 3:
			$im = @imagecreatefrompng($im);
			break;
		}

		switch ($Imagedata[2]){
			case 1:
			@imagegif($im,$savepath); 
			break;
			case 2:
			@imagejpeg($im,$savepath,100); 
			break;
			case 3:
			@imagepng($im,$savepath); 
			break;
		}

		@imagedestroy($im); 
			 
	}
	
	function UploadAvatar(){
		
		if(!is_dir(C('S_ATTACHMENT_DIR').'/avatar')) {
			@mkdir(C('S_ATTACHMENT_DIR').'/avatar',0777);
			WriteFile(C('S_ATTACHMENT_DIR').'/avatar/index.html','');
		}	

		$sitefileform=array("jpg","gif","png");
		$fileheadertype=array('jpg'=>255216,'gif'=>7173,'png'=>13780);
		$fileheader=$this->GetFileHeader($_FILES['file']['tmp_name']);

		//$fileheadertype=array('jpg'=>'image/jpeg','gif'=>'image/gif','png'=>'image/png');
		//$fileheader=$this->GetFileInfoMIME($_FILES['file']['tmp_name']);

		$fileform=GetFileForm($_FILES['file']['name']); 

		$is_type=0;

		foreach($sitefileform as $forms){

			if($fileform==$forms && $fileheader==$fileheadertype[$forms] && $_FILES['file']['size']<1048576){

				$newfilepath=$this->FilePath(C('S_UPLOAD_DIR'),$forms,array('thumb'));

				@$this->IsPhoto($_FILES['file']['tmp_name'],$newfilepath[1]);

				if(is_file(FOXPHP_PATH.'/'.$newfilepath[1])){
					$is_type=1;
				}else{
					$is_type=0;
				}

				DelFile(FOXPHP_PATH.'/'.$newfilepath[1]);  
			}

		}

		if($is_type){			  

			$udir=substr($this->uid,-2,2);

			$avatar =$udir.'/'.$this->uid.'.'.$fileform;
			
			$this->avatar=$avatar;

			$this->where(" uid=$this->uid ")->save();
			
			$this->MakeBigAvatar($fileform);

			$this->MakeMiddleAvatar($fileform);

			$this->MakeSmallAvatar($fileform);

			return true;

		}else{

			return false;

		}
		  
		
	}

	
	//生成大图 200px * 200px
	function MakeBigAvatar($fileform){
		  
		$dir=C('S_ATTACHMENT_DIR').'/avatar/big';
 
		$middle=$this->AvatarPath($dir,$fileform);

		$image=new \Think\Image();

		$image->open($_FILES['file']['tmp_name']);

		$image->thumb(200,200,\Think\Image::IMAGE_THUMB_CENTER)->save($middle);
		
		return true;
	}
	

	//生成中图 120px * 120px
	function MakeMiddleAvatar($fileform){
		  
		$dir=C('S_ATTACHMENT_DIR').'/avatar/middle';

		$middle=$this->AvatarPath($dir,$fileform);

		$image=new \Think\Image();

		$image->open($_FILES['file']['tmp_name']);

		$image->thumb(120,120,\Think\Image::IMAGE_THUMB_CENTER)->save($middle);
		
		return true;

	}
	
	//生成小图 48px * 48px
	function MakeSmallAvatar($fileform){
		
		//生成小图地址 
		$dir=C('S_ATTACHMENT_DIR').'/avatar/small';

		$middle=$this->AvatarPath($dir,$fileform);

		$image=new \Think\Image();

		$image->open($_FILES['file']['tmp_name']);

		$image->thumb(48,48,\Think\Image::IMAGE_THUMB_CENTER)->save($middle);
		
		return true;
		
	}
	
	function AvatarPath($dir,$filetype){
		
		if(!is_dir($dir)) {
			@mkdir($dir,0777);
			WriteFile($dir.'/index.html','');
		}	 

		$dir1=substr($this->uid,-2,2);

		$filedir=$dir.'/'.$dir1;

		if(!is_dir($filedir)) {
			@mkdir($filedir,0777);
			WriteFile($filedir.'/index.html','');
		}

		//return $filedir.'/'.$this->uid.'.'.$filetype;
		return $filedir.'/'.$this->uid.'.jpg';
	}
	
	
	function GetFileHeader($filename){
		$file= @fopen($filename, "rb");
		$bin= fread($file, 2); 
		fclose($file);
		$strInfo  = @unpack("C2chars", $bin);
		return intval($strInfo['chars1'].$strInfo['chars2']);
	}
	
	function GetFileInfoMIME($filename){
		$finfo = finfo_open(FILEINFO_MIME);
		$mimetype = finfo_file($finfo, $filename);
		finfo_close($finfo);
		$mimetypearr=explode(';',$mimetype);
		return $mimetypearr[0];
	}	
	
	
	//数据操作--------------------------------------------------------------------------------//
	
	//获取用户使用条数
	function GetCountData(){
		return intval($this->where(" uid=$this->uid ")->count("uid"));
	}

	//获取一维数据
	function GetArrayData($id=0){
		$id=!empty($id) ? intval($id) : 0 ;
		$result=$this->where(" id=$id ")->find();
		if(intval($result['id'])>0){
			return $result;
		}else{
			$this->error='数据不存在或有误!';
			return false;
		}
	}
	
	//获取会员所有数据
	function GetArrayAllData($num=3){
		$result=$this->where(" uid=$this->uid ")->limit($num)->order('id ASC')->select();
		if(is_array($result)){
			return $result;
		}else{
			$this->error='数据不存在或有误!';
			return false;
		}
	}
	
	//修改信息
	function EditMemberData($formatdata,$id=0){
		$id= $id>0 ? $id : intval($_POST['id']);
		if ($this->create($formatdata)){
			if($this->where(" id=$id ")->save()){
				return true;
			}
		}
		$this->error=$this->getError();
		return false;
	}
	
	//删除信息
	function DeleteMemberData(){
		$id=intval($_POST['id']);
		if($id){
			$this->where(" id=$id ")->delete();
			return true;
		}else{
			return false;
		}
	}
	
	//插入会员信息
	function InsertMemberData($formatdata,$num=3){
		if($this->GetCountData()<$num){
			return $this->InsertData($formatdata);
		}else{
			$this->error='您已经添加'.$num.'条了!';
			return false;
		}
	}
	
	//插入数据
	function InsertData($formatdata){
		if ($this->create($formatdata)){
			return $this->add();
		}
		$this->error=$this->getError();
		return false;
	}
	
	//修改密码
	function ChangePassword($uid=0,$password=null){
		if(!$uid && !$password){
			//新密码
			$password=I('post.password');	
			$confirmpassword=I('post.confirmPassword');	
			if($password!=$confirmpassword){
				$this->error='新密码和确认密码不相同!';
				return false;
			}
			
			$password=trim(strip_tags($password));
			if(preg_match("/\s/",$password)) {
				$this->error='对不起!密码格式有误！';
				return false;
			}
			
			$uid=$this->uid;
			//验证原密码
			$member=$this->token(false)->where(" uid=%d ",$uid)->find();
			
			$userkey=PasswordKey($member['username'],$_POST['passwordold'],$member['powercode']);
		}else{
			$member=$this->token(false)->where(" uid=%d ",$uid)->find();
			$userkey=$member['password'];
		}

		if($this->token(false)->where(" uid=$uid AND password='$userkey' ")->count()){

			$newkey=PasswordKey($member['username'],$password,$member['powercode']);

			//本站
			$this->token(false)->where(" uid=$uid ")->save(array('password'=>$newkey));

			//UC
			if($uclient=GetClient(array('username'=>$member['username'],'password'=>$_POST['passwordold']))){
				$uclient->user_edit($password,1);
			}
			
			$this->success='修改成功！';
			return true;
		}else{
			$this->error='原密码有误!';
		}		

	   	return false;

	}
	
	
	//服务商列表
	function GetShopList($ismap=''){
		$pagenum=intval($_GET['p']);
		
		$selectwhere=$this->SelectRencaiWhere();
		$wheresql=$selectwhere[0];
		$order=$this->OrderRencaiWhere();
		
		if($ismap=='map'){
			$shownum=100;
		}else{
			$shownum=20;
		}
		
		//数据-------------------------------
		$list=$this->token(false)->where($wheresql,$selectwhere[4])->order($order)->page($pagenum,$shownum)->select();

		//页码-------------------------------
		$count=$this->token(false)->where($wheresql,$selectwhere[4])->count();
		$Page = new \Think\Page($count,$shownum);
	

		$newpage=str_replace("Index/index/catid/",'',$Page->show());
		$newpage=str_replace("Index/index/",'',$newpage);
		$newpage=str_replace("/m/fuwu",'',$newpage);
		$newpage=str_replace("realname/",'r',$newpage);
		$newpage=str_replace("order/",'o',$newpage);
		$newpage=str_replace("search",'s',$newpage);
		$newpage=str_replace("time/",'t',$newpage);
		$newpage=str_replace("city/",'c',$newpage);
		return array('list'=>$list,'page'=>$newpage,'cityname'=>$selectwhere[1],'category'=>$selectwhere[2],'route'=>$selectwhere[3],'search'=>$selectwhere[4],'categoryone'=>$selectwhere[5],'categorycity'=>$selectwhere[6]);
	}
	
	//服务商排序SQL
	function OrderRencaiWhere(){
		$ordersql='top DESC,dateline DESC';
		
		$order=intval($_GET['order']);
		if($order==1){
			$ordersql='top DESC';
		}elseif($order==2){
			$ordersql='dateline DESC';
		}elseif($order==3){
			$ordersql='seller_haoping DESC';
		}
		
		return $ordersql;
	}
	
	//服务商筛选SQL
	function SelectRencaiWhere(){
		$where=' isshop=1 ';
				
		$haoping=intval($_GET['haoping']);
		if($haoping==1){
			$where.=' AND seller_haoping>=100 ';
		}elseif($haoping==2){
			$where.=' AND seller_haoping>=1000 ';
		}elseif($haoping==3){
			$where.=' AND seller_haoping>=10000 ';
		}

		$time=intval($_GET['time']);
		if($time==1){
			$where.=" AND dateline>=UNIX_TIMESTAMP(timestamp(date(sysdate()))) AND dateline<=(UNIX_TIMESTAMP()+86400) ";
		}elseif($time==2){
			$where.=" AND dateline>=(UNIX_TIMESTAMP()-86400) AND dateline<=UNIX_TIMESTAMP(timestamp(date(sysdate()))) ";
		}elseif($time==3){
			$where.=" AND dateline>=(UNIX_TIMESTAMP()-259200) AND dateline<=UNIX_TIMESTAMP(timestamp(date(sysdate()))) ";
		}elseif($time==4){
			$where.=" AND dateline>=(UNIX_TIMESTAMP()-604800) AND dateline<=UNIX_TIMESTAMP(timestamp(date(sysdate()))) ";
		}elseif($time==5){
			$where.=" AND dateline>=(UNIX_TIMESTAMP()-2592000) AND dateline<=UNIX_TIMESTAMP(timestamp(date(sysdate()))) ";
		}
		
		$order=intval($_GET['order']);
		if($order==1){
			$where.=' AND top=1 ';
		}
		
		//分类
		$route='';
		if(preg_match('/^[a-z]+$/i',$_GET['catid'])){ 
			$route=$_GET['catid'];
			$categoryone= M('Category')->token(false)->where(" route='$route' ")->find();
			if(!empty($categoryone)){
				$catid=$categoryone['catid'];
				$route=$categoryone['route'];
				if(!empty($categoryone['nexts'])){
					$categoryid=$categoryone['nexts'];
					$where.=" AND catid IN($categoryid) ";
				}
				$category= M('Category')->token(false)->where(" upid=$catid AND task=1 ")->select();
			}
		}else{
			//1级
			$category= M('Category')->token(false)->where(" upid=0 AND task=1 ")->select();
		}
		
		if(empty($category)){
			$category=array($categoryone);
		}

		$city=intval($_GET['city']);
		$cityname='';
		if($city){
			$cityarr= M('CategoryCity')->token(false)->where(" catid=$city ")->find();
			if(!empty($cityarr)){
				$cityid=$cityarr['nexts'];
				$cityname=$cityarr['name'];
				if($cityid){
					$where.=" AND distid IN($cityid) ";
				}
			}
		}
		
		//O2O
		$categorycity=array();
		if(C('otoo_open')==1 && $city){
			$categorycity=M('CategoryCity')->token(false)->where(" upid=$city ")->select();
			if(empty($categorycity)){
				$categorycity=array($cityarr);
			}
		}
		
		//搜索
		$search=String::msubstr(I('get.search'),0,12,C('S_CHARSET'),false);
		$search=strip_tags($search);
		$search=trim(htmlspecialchars($search,ENT_QUOTES,C('S_CHARSET')));
		if(!empty($search)){
			$where.=" AND username like '%%%s%%'";  
		}
		
		return array($where,$cityname,$category,$route,$search,$categoryone,$categorycity);
	}
	
	//获取数据
	function GetCustomData($where='',$order='',$limit=10){
		return $this->token(false)->where($where)->order($order)->limit($limit)->select();
	}
	
	
	function UploadLogo(){
		
		$shop_logo_color=String::msubstr(I('post.shop_logo_color'),0,6,C('S_CHARSET'),false);
		if(preg_match('/^[0-9a-z]+$/i',$shop_logo_color)){ 
			$data['shop_logo_color']=$shop_logo_color;
		}
		
		$model=new \Upload\Model\FileModel();
		$file=$model->StartUpload(1);
		$fid=$file['id'];
		if(!empty($fid)){
			$data['shop_logo']=$file['filepath'];
			$data['shop_logo_id']=$file['id'];
			$member=$this->UidGetMember($this->uid);
			if(!empty($member['shop_logo_id'])){
				$model->DeleteUpload($member['shop_logo_id']);
			}
			if ($this->token(false)->create($data)){
				if($this->token(false)->where(" uid=$this->uid ")->save()){
					$model->token(false)->where(" fid=$fid ")->save(array('isuse'=>1));
					return true;
				}
			}
		}
		
		$this->error=$model->getError();
		return false;

	}
	
	//登录微博
	function LoginWeiBo($post=array()){
		
		$post['apiname']=String::msubstr($post['apiname'],0,20,C('S_CHARSET'),false);
		$post['apiname']=strip_tags($post['apiname']);
		$post['apiname']=trim(htmlspecialchars($post['apiname'],ENT_QUOTES,C('S_CHARSET')));
		$post['dateline']=NowTime();
		
		$type=intval($post['type']);
		if($this->uid>0){
			//绑定
			if(M('SnsApi')->token(false)->where(" uid=$this->uid AND type=$type ")->count()){
				//修改
				return M('SnsApi')->token(false)->where(" uid=$this->uid AND type=$type ")->save($post);
			}else{
				if (M('SnsApi')->token(false)->create($post)){
					if($id=M('SnsApi')->token(false)->add()){
						return $id;
					}
				}
			}
			
			return false;
			
		}else{
			//登录
			$apikey=$post['apikey'];
			$user=M('SnsApi')->token(false)->where(" apikey='$apikey' AND type=$type ")->find();
			if(!empty($user['uid'])){
				
				$userarray=$this->UidGetMember($user['uid']);
				
				if(!empty($userarray['uid'])){	
				
					//权限
					$auth=new \Think\Auth();
					if(!$auth->check(MODULE_NAME."/".CONTROLLER_NAME."/".ACTION_NAME,$userarray['uid'])){
						$this->error='对不起!该用户名已被锁定,请联系网站客服解锁!';
						return false;
					}
					
					session('USER_USERID',$userarray['uid']);
					session('USER_USERTYPE',$userarray['usertype']);
					session('USER_USERNAME',$userarray['username']);
					
					return true;
				}else{
					if(!$this->LoginError()){
						return false;
					}
					$this->error='对不起!用户名或密码有误!';
					return false;
				}
				
			}
		}
	}
	
	//购买VIP
	function BuyVip(){

		$member=$this->UidGetMember($this->uid);
		
		//是否开店
		if(!$member['isshop']){
			$this->error='对不起!请开店后操作!';
			return false;
		}
		
		$consume=new \Consume\Model\ConsumeModel();
		if($consume->PayVip($member,4,C('buyviptime'),C('buyvipmoney'))){
			return true;
		}
		$this->error=$consume->getError();
		return false;
	}
}

?>